//
//  MCHealthUtil.m
//  MoveVirtualCurrency
//
//  Created by LiuYing on 2018/7/2.
//  Copyright © 2018年 Test. All rights reserved.
//

#import "MCHealthUtil.h"
#import <HealthKit/HealthKit.h>

// 一天的秒数
#define kDAYSECS (86400)

@implementation MCHealthUtil

+ (NSDateComponents *)dateComponentOfNow {
    //获取当前时间 (零时区)
    NSDate *now = [NSDate date];
    return [self dateComponentForDate:now];
}

+ (NSDateComponents *)dateComponentForDate:(NSDate *)date {
    
    NSCalendar *calender = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents *dateComponent = [calender components:unitFlags fromDate:date];
    
    return dateComponent;
}

#pragma mark - query predicate
#pragma mark -

+ (NSPredicate *)todaySetupCountPredicate {

    NSDate *nowDay  = [self todayDate];
    NSDate *nextDay = [self tomorrowDate];
    return [self queryFromDate:nowDay toDate:nextDay];
}

+ (NSPredicate *)lastSevenDaysSetupCountPredicate {

    NSDate *nextDay      = [self tomorrowDate];
    NSDate *sevenDaysAgo = [self sevenDaysAgoDate];
    return [self queryFromDate:sevenDaysAgo toDate:nextDay];
}

+ (NSPredicate *)lastThirtyDaysStepCountPredicate {
    NSDate *nextDay       = [self tomorrowDate];
    NSDate *thirtyDaysAgo = [self thirtyDaysAgo];
    return [self queryFromDate:thirtyDaysAgo toDate:nextDay];
}

+ (NSPredicate *)queryFromDate:(NSDate *)startDate toDate:(NSDate *)endDay {
    return [HKQuery predicateForSamplesWithStartDate:startDate
                                             endDate:endDay
                                             options:(HKQueryOptionNone)];
}

+ (NSDate *)todayDate {
    return [self dateWithTimeIntervalSinceNow:NO secs:0];
}

+ (NSDate *)tomorrowDate {
    return [self dateWithTimeIntervalSinceNow:NO secs:kDAYSECS];
}

+ (NSDate *)sevenDaysAgoDate {
    return [self dateWithTimeIntervalSinceNow:YES secs:(kDAYSECS * 6)];
}

+ (NSDate *)thirtyDaysAgo {
    return [self dateWithTimeIntervalSinceNow:YES secs:(kDAYSECS * 29)];
}


+ (NSDate *)dateWithTimeIntervalSinceNow:(BOOL)isBefor secs:(NSTimeInterval)secs {
    
    NSDateComponents *dateComponent = [self dateComponentOfNow];
    
    int hour   = (int)[dateComponent hour];
    int minute = (int)[dateComponent minute];
    int second = (int)[dateComponent second];
    
    NSTimeInterval interval = -(hour * 3600 + minute * 60 + second);
    if (isBefor) {
        interval -= secs;
    } else {
        interval += secs;
    }
    return [NSDate dateWithTimeIntervalSinceNow:interval];
}

@end
